package com.example.weather_app.diary;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import androidx.core.app.NotificationCompat;

import com.example.weather_app.R;

public class ReminderService extends Service {
    private static final String CHANNEL_ID = "diary_reminder_channel";
    private static final String TAG = "ReminderService";
    private DiaryDao diaryDao;
    private SimpleDateFormat dateFormat;

    @Override
    public void onCreate() {
        super.onCreate();
        diaryDao = new DiaryDao(this);
        dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        checkReminders();
        return START_STICKY;
    }

    private void checkReminders() {
        List<Diary> reminderDiaries = diaryDao.getReminderDiaries();
        Calendar now = Calendar.getInstance();
        for (Diary diary : reminderDiaries) {
            String reminderTime = diary.getReminderTime();
            try {
                Date reminderDate = dateFormat.parse(reminderTime);
                Calendar reminderCal = Calendar.getInstance();
                reminderCal.setTime(reminderDate);
                if (now.after(reminderCal)) {
                    showReminderNotification(diary.getId());
                    // 可以考虑在提醒后将提醒时间置空，避免重复提醒
                    diary.setReminderTime(null);
                    diaryDao.updateDiary(diary);
                }
            } catch (ParseException e) {
                Log.e(TAG, "Error parsing reminder time: " + reminderTime, e);
            }
        }
    }

    private void showReminderNotification(String diaryId) {
        Diary diary = diaryDao.getDiaryById(diaryId);
        if (diary != null) {
            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            Intent notificationIntent = new Intent(this, DiaryDetailActivity.class);
            notificationIntent.putExtra("diaryId", diaryId);
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

            PendingIntent contentIntent = PendingIntent.getActivity(
                    this,
                    diaryId.hashCode(),
                    notificationIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
            );

            // 构建通知
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
                    .setSmallIcon(R.drawable.ic_reminder)
                    .setContentTitle("日记提醒")
                    .setContentText(diary.getTitle())
                    .setContentIntent(contentIntent)
                    .setAutoCancel(true)
                    .setPriority(NotificationCompat.PRIORITY_HIGH);

            // Android 8.0+ 需要创建通知渠道
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                CharSequence name = "日记提醒";
                String description = "日记应用的提醒通知";
                int importance = NotificationManager.IMPORTANCE_HIGH;
                NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
                channel.setDescription(description);
                notificationManager.createNotificationChannel(channel);
            }

            notificationManager.notify(diaryId.hashCode(), builder.build());
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}